package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-09-08
 */
@SuppressWarnings("all")
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PatientService patientService;

    //登录接口
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //1.非空判断
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //校验参数
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "数据为空");
        }

        //2.手机验证码校验
        //获取redis存储验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new YyghException(20001, "验证码校验失败");
        }
        //判断是手机验证码登录还是微信绑定手机号
        //获取页面传过来的openid值
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)) {//手机验证码登录
            //3.判断手机号是否是第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            //如果是第一次先注册
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                userInfo.setAuthStatus(0);
                baseMapper.insert(userInfo);
            }
            //如果不是 校验状态
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户被锁定");
            }
            Map<String, Object> map = get(userInfo);
            return map;
        } else {//openid不为空 微信登录->绑定手机号
            //创建userInfo对象,用于存放所有最终数据
            UserInfo userInfoFinal = new UserInfo();
            //根据手机号查询对应数据 封装到userInfoFinal
            UserInfo userInfoPhone = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
            if (userInfoPhone != null) {//目前微信绑定的手机号在数据库中存在
                BeanUtils.copyProperties(userInfoPhone, userInfoFinal);
                //根据手机号删除数据库存在的信息
                baseMapper.delete(new QueryWrapper<UserInfo>().eq("phone", phone));
            }
            //根据openid查询微信信息
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            UserInfo userInfoWX = baseMapper.selectOne(wrapper);
            //封装微信信息到userInfoFinal
            userInfoFinal.setOpenid(userInfoWX.getOpenid());
            //我竟然机智的把微信信息的手机号给封装进去了 空串覆盖了原来已有的手机号!
            userInfoFinal.setNickName(userInfoWX.getNickName());
            userInfoFinal.setId(userInfoWX.getId());
            userInfoFinal.setPhone(phone);
//            userInfoFinal.setStatus(1);
            //修改
            baseMapper.updateById(userInfoFinal);
            //注 数据库中的信息status是1因为插入时为null 插入后默认为1    但是此时判断条件用的是未插入时的数据 status为null
            //若手机号被禁用 再用微信绑定手机号还是被禁用
            //个人认为需要再查询一遍数据库
            userInfoFinal = baseMapper.selectById(userInfoFinal.getId());
            if (userInfoFinal.getStatus() == 0) {
                throw new YyghException(20001, "用户已经禁用");
            }
            Map<String, Object> map = get(userInfoFinal);
            return map;
        }
    }


    private Map<String, Object> get(UserInfo userInfo) {
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //根据userid和name生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfo findUserByOpenid(String openid) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    //提交用户认证信息
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据userid查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //设置认证数据
        userInfo.setName(userAuthVo.getName()); //姓名
        userInfo.setCertificatesType(userAuthVo.getCertificatesType()); //证件类型
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo()); //身份号码
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl()); //证件图片路径
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus()); //认证中

        //修改
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {//模糊查询
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }
        Page<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });

        return pages;
    }


    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }

    //这里的userId实质是user_info表的id
    @Override
    public void lock(Long userId, Integer status) {
        if (status == 0 || status == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> showUserDetail(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("userInfo", userInfo);
        map.put("patientList", patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        //2通过 1不通过
        if (authStatus.intValue() == 2 || authStatus.intValue() == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
